package com.ysq.www.api.login.controller;


import com.ysq.www.common.annotation.AuthToken;
import com.ysq.www.common.exception.BaseException;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.result.ResultStatusCode;
import com.ysq.www.common.utils.Comm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    @Value("${file-save-path}")
    private String fileSavePath;

    /**
     * 上传图片
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload/image")
    @AuthToken
    public ResultMsg uploadImage(MultipartFile file, HttpServletRequest request){
        //文件名后半段
        String directory = simpleDateFormat.format(new Date());
        /**
         * 查看文件是否存在
         */
        File dir = new File(fileSavePath+directory);
        if (!dir.exists()){
            dir.mkdirs();
        }
        log.info("图片上传保存位置:"+fileSavePath+directory);
        //重新设置文件名
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = Comm.getUUID()+suffix;
        //创建新文件
        File newFile = new File(fileSavePath+directory+newFileName);
        //复制
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() +
                    ":" + request.getServerPort() + "/images/" + directory + newFileName;
            return ResultMsg.UPLOAD_SUCCESS.setNewData(url);
        }catch (Exception e){
            log.error("上传图片失败!内部错误!");
            e.printStackTrace();
            throw new BaseException(ResultStatusCode.UPLOAD_ERROR);
        }
    }


    /**
     * 上传多张图片并返回地址列表
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/batchUpload")
    @AuthToken
    public ResultMsg batchUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request){
        log.info("数组长度:"+files.length);
        List<String> urlList = new ArrayList<>();
        for (MultipartFile file : files) {
            //文件名后半段
            String directory = simpleDateFormat.format(new Date());
            /**
             * 查看文件是否存在
             */
            File dir = new File(fileSavePath+directory);
            if (!dir.exists()){
                dir.mkdirs();
            }
            log.info("图片上传保存位置:"+fileSavePath+directory);
            //重新设置文件名
            //后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = Comm.getUUID()+suffix;
            //创建新文件
            File newFile = new File(fileSavePath+directory+newFileName);
            //复制
            try {
                file.transferTo(newFile);
                String url = request.getScheme() + "://" + request.getServerName() +
                        ":" + request.getServerPort() + "/images/" + directory + newFileName;
                urlList.add(url);
            }catch (Exception e){
                log.error("上传图片失败!内部错误!");
                e.printStackTrace();
                throw new BaseException(ResultStatusCode.UPLOAD_ERROR);
            }
        }
        return ResultMsg.UPLOAD_SUCCESS.setNewData(urlList);
    }


    /**
     * 删除图片
     * @param pcUrl
     * @return
     */
    @GetMapping("/deletePC")
    @AuthToken
    public ResultMsg deletePC(String pcUrl){
        File file = new File(pcUrl);
        if (file.exists()){
            if (file.delete()){
                return ResultMsg.DELETE_SUCCESS;
            }else return ResultMsg.DELETE_ERROR;
        }else return ResultMsg.DELETE_ERROR.setNewMsg("文件不存在");
    }

}
